﻿using System;
using System.Data;
using System.Data.SqlClient;

namespace BLL.Services.Ratings
{
    public class RatingCollection
    {
        private readonly string _connectionString;

        public RatingCollection(string connectionString)
        {
            _connectionString = connectionString;
        }

        public void SetRating(Rating model)
        {
            using (var conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                var cmd = StoredProcedures.Ratings.Insert(conn, model.UserId, model.BookId, model.RateValue);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        if (reader.HasRows)
                        {
                            model = GetRating(reader);
                        }
                    }
                }
            }
        }

        public BookRating GetBookRating(int bookId, int userId)
        {
            var bookRating = new BookRating();
            using (var conn = new SqlConnection(_connectionString))
            {
                conn.Open();
                var cmd = StoredProcedures.Ratings.GetBookRating(conn, bookId, userId);
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        bookRating.Rating = Convert.ToInt32(reader[0] as string ?? "0");
                        bookRating.IsCanRate = userId != 0 && (reader[1] as string) == "0";
                    }
                }
            }
            return bookRating;
        }

        private static Rating GetRating(SqlDataReader reader)
        {
            var rating = new Rating
                {
                    UserId = reader.GetInt32(0), 
                    BookId = reader.GetInt32(1), 
                    RateValue = reader.GetInt32(2)
                };

            return rating;
        }
    }
}
